/*
 * Copyright (c) 2006-2020, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2020-08-10     RT-Thread    first version
 */

#include <rtthread.h>
#include <board.h>
#include <rtdevice.h>

#define DBG_TAG "main"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>

#define LED0_PIN    GET_PIN(E, 5)
#define LED1_PIN    GET_PIN(E, 6)

#define DAC_SD      GET_PIN(A, 3)

int main(void)
{
    int count = 3;
    uint16_t len = 0;
    uint8_t data[128] = {0};
    char buf[] = "hello rt-thread!\r\n";

    /* set LED0 pin mode to output */
    rt_pin_mode(LED0_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(LED1_PIN, PIN_MODE_OUTPUT);

    rt_pin_mode(DAC_SD, PIN_MODE_OUTPUT);
    rt_pin_write(DAC_SD, PIN_LOW);

    rt_device_t dev = rt_device_find("vcom");
    if (dev)
        rt_device_open(dev, RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX);
    else
        rt_kprintf("vcom null\r\n");

//    return RT_EOK;
    while (++count)
    {
        /* set LED0 pin level to high or low */
        rt_pin_write(LED1_PIN, count % 2);
//        LOG_D("Hello RT-Thread!");
        rt_thread_mdelay(100);
        if (dev)
          rt_device_write(dev, 0, buf, rt_strlen(buf));
        if (dev)
        {
          len = rt_device_read(dev, 0, data, sizeof(data));
          if(len != 0)
            LOG_HEX("vcom", 20, data, len);
        }
    }
    return RT_EOK;
}

void mnt_thread_entery (void *parameter)
{
    while(1)
    {
        if(rt_device_find("sd0") != RT_NULL)
        {
            if (dfs_mount("sd0", "/", "elm", 0, 0) != 0)
                rt_kprintf("file system mount failed!\n");
            else
                rt_kprintf("file system mount success!\n");
            break;
        }
        rt_thread_mdelay(100);
    }
}

//int mnt_init(void)
//{
//    rt_thread_t tid = rt_thread_create("sd_mnt", mnt_thread_entery, RT_NULL, 4096, 11, 10);
//    if(tid)
//        rt_thread_startup(tid);
//    return 0;
//}
//INIT_APP_EXPORT(mnt_init);

#define APP_ADDRESS             QSPI_BASE
int ota_app_vtor_reconfig(void)
{
    #define NVIC_VTOR_MASK   0xFFFFFF80
    /* Set the Vector Table base location by user application firmware definition */
    SCB->VTOR = APP_ADDRESS & NVIC_VTOR_MASK;
    return 0;
}
INIT_BOARD_EXPORT(ota_app_vtor_reconfig);
